import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../config/api_config.dart';
import '../models/courier_company.dart';
import '../models/tracking_info.dart';

class ApiResponse<T> {
  final bool success;
  final String message;
  final int code;
  final T? data;
  final String? requestId;

  ApiResponse({
    required this.success,
    required this.message,
    required this.code,
    this.data,
    this.requestId,
  });
}

class ApiService {

  /// 查询快递物流信息
  /// 
  /// [number] 快递编号
  /// [com] 快递公司编码（可选，默认自动识别）
  /// [phone] 寄/收件人手机号后四位（顺丰快递和中通快递必填）
  static Future<ApiResponse<TrackingInfo>> queryPackage({
    required String number,
    String? com,
    String? phone,
  }) async {
    const timeout = Duration(seconds: 15); // 设置15秒超时
    
    try {
      final response = await http
          .post(
            Uri.parse(ApiConfig.trackingEndpoint),
            body: {
              'token': ApiConfig.apiToken,
              'number': number,
              if (com != null) 'com': com,
              if (phone != null) 'phone': phone,
            },
          )
          .timeout(timeout);

      if (response.statusCode == 200) {
        final jsonData = json.decode(utf8.decode(response.bodyBytes));
        
        if (jsonData['success'] == true) {
          final trackingInfo = TrackingInfo.fromJson(jsonData['data']);
          return ApiResponse(
            success: true,
            message: jsonData['message'] ?? 'success',
            code: jsonData['code'] ?? 200,
            data: trackingInfo,
            requestId: jsonData['request_id'],
          );
        } else {
          return ApiResponse(
            success: false,
            message: jsonData['message'] ?? '查询失败',
            code: jsonData['code'] ?? 0,
            requestId: jsonData['request_id'],
          );
        }
      } else {
        return ApiResponse(
          success: false,
          message: _getErrorMessage(response.statusCode),
          code: response.statusCode,
        );
      }
    } on TimeoutException {
      return ApiResponse(
        success: false,
        message: '请求超时，请检查网络连接后重试',
        code: -1,
      );
    } on FormatException {
      return ApiResponse(
        success: false,
        message: '服务器返回数据格式错误',
        code: -1,
      );
    } catch (e) {
      return ApiResponse(
        success: false,
        message: '网络连接失败，请检查网络设置',
        code: -1,
      );
    }
  }

  /// 获取快递公司列表
  static Future<ApiResponse<List<CourierCompany>>> getCourierCompanies() async {
    const timeout = Duration(seconds: 15); // 设置15秒超时
    
    try {
      final response = await http
          .post(
            Uri.parse(ApiConfig.courierListEndpoint),
            body: {
              'token': ApiConfig.apiToken,
            },
          )
          .timeout(timeout);

      if (response.statusCode == 200) {
        final jsonData = json.decode(utf8.decode(response.bodyBytes));
        
        if (jsonData['success'] == true) {
          final companies = (jsonData['data'] as List<dynamic>)
              .map((e) => CourierCompany.fromJson(e as Map<String, dynamic>))
              .toList();
          
          return ApiResponse(
            success: true,
            message: jsonData['message'] ?? 'success',
            code: jsonData['code'] ?? 200,
            data: companies,
            requestId: jsonData['request_id'],
          );
        } else {
          return ApiResponse(
            success: false,
            message: jsonData['message'] ?? '获取失败',
            code: jsonData['code'] ?? 0,
            requestId: jsonData['request_id'],
          );
        }
      } else {
        return ApiResponse(
          success: false,
          message: _getErrorMessage(response.statusCode),
          code: response.statusCode,
        );
      }
    } on TimeoutException {
      return ApiResponse(
        success: false,
        message: '请求超时，请检查网络连接后重试',
        code: -1,
      );
    } catch (e) {
      return ApiResponse(
        success: false,
        message: '网络连接失败，请检查网络设置',
        code: -1,
      );
    }
  }

  /// 根据HTTP状态码返回友好的错误信息
  static String _getErrorMessage(int statusCode) {
    switch (statusCode) {
      case 400:
        return '请求参数错误';
      case 401:
        return 'API Token 无效，请检查配置';
      case 403:
        return '请求被拒绝，请检查权限';
      case 404:
        return '请求的资源不存在';
      case 429:
        return '请求过于频繁，请稍后再试';
      case 500:
        return '服务器内部错误，请稍后重试';
      case 503:
        return '服务暂时不可用，请稍后重试';
      default:
        return '网络请求失败 (错误码: $statusCode)';
    }
  }
}

